/*
 * NESController.cpp
 *
 *  Created on: Oct 23, 2012
 *      Author: nam20485
 */

#include "NESController.h"
#include "Arduino.h"

NESController::NESController(int dataPin, int strobePin, int clockPin)
	: DATA_PIN(dataPin)
	, STROBE_PIN(strobePin)
	, CLOCK_PIN(clockPin)
{
}

NESController::~NESController()
{
}

bool NESController::getButtonState(BUTTON button) const
{
	int state = getButtonState();
	return (state & button);
}

//digitalWrite(NES_STROBE,LOW);
//buttons  = readNesBit(buttonA);
//buttons |= readNesBit(buttonB);
//buttons |= readNesBit(buttonSelect);
//buttons |= readNesBit(buttonStart);
//dpad  = readNesBit(0x01);
//dpad |= readNesBit(0x02);
//dpad |= readNesBit(0x04);
//dpad |= readNesBit(0x08);

//Bring the STROBE wire LOW (default should be HIGH)
//Read each button bit:
//Set the STROBE wire to HIGH again (ready for next time...)

const int NESController::getButtonState() const
{
	int state = 0;

	digitalWrite(STROBE_PIN, LOW);

	if (readNextBit())	state |= A;
	if (readNextBit())	state |= B;
	if (readNextBit())	state |= SELECT;
	if (readNextBit())	state |= START;
	if (readNextBit())	state |= UP;
	if (readNextBit())	state |= DOWN;
	if (readNextBit())	state |= LEFT;
	if (readNextBit())	state |= RIGHT;

	digitalWrite(STROBE_PIN, HIGH);

	return state;
}

//Bring the STROBE wire LOW (default should be HIGH)
//For each button:
//	Read the DATA line to get the button state
//	Make the CLOCK line go LOW then HIGH again to select the next button (default is HIGH)
//Set the STROBE wire to HIGH again (ready for next time...)

bool NESController::readNextBit() const
{
	// is button on if signal is low or high?
	bool set = digitalRead(DATA_PIN);	// high is being used
	digitalWrite(CLOCK_PIN, LOW);
	digitalWrite(CLOCK_PIN, HIGH);

	return set;
}

void NESController::initialize()
{
	// set each pin's mode and then high
	pinMode(DATA_PIN, INPUT);
	digitalWrite(DATA_PIN, HIGH);

	pinMode(STROBE_PIN, OUTPUT);
	digitalWrite(STROBE_PIN, HIGH);

	pinMode(CLOCK_PIN, OUTPUT);
	digitalWrite(CLOCK_PIN, HIGH);
}


